<template>
  <div class="point-edit">
    <div class="page-header">
      <div class="back-btn">
        <router-link to="/admin/points" class="admin-btn">
          返回列表
        </router-link>
      </div>
      <div class="header-title">
        <h2>{{ isEditMode ? '编辑商品' : '添加商品' }}</h2>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="error" class="error-container">
      <p class="error-message">{{ error }}</p>
      <button class="admin-btn" @click="retryLoading">重试</button>
    </div>

    <div v-else class="point-form">
      <div class="form-section">
        <div class="form-group">
          <label for="product-name" class="form-label">商品名称 <span class="required">*</span></label>
          <input 
            type="text" 
            id="product-name" 
            v-model="product.name" 
            class="admin-form-input" 
            :class="{ 'input-error': validationErrors.name }"
            placeholder="请输入商品名称"
          />
          <div v-if="validationErrors.name" class="error-message">{{ validationErrors.name }}</div>
        </div>

        <div class="form-row">
          <div class="form-group half">
            <label for="product-category" class="form-label">商品分类 <span class="required">*</span></label>
            <select 
              id="product-category" 
              v-model="product.category" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.category }"
            >
              <option value="">请选择分类</option>
              <option value="digital">数字商品</option>
              <option value="physical">实物商品</option>
              <option value="voucher">优惠券</option>
              <option value="donation">公益捐赠</option>
            </select>
            <div v-if="validationErrors.category" class="error-message">{{ validationErrors.category }}</div>
          </div>

          <div class="form-group half">
            <label for="product-points" class="form-label">积分价格 <span class="required">*</span></label>
            <input 
              type="number" 
              id="product-points" 
              v-model.number="product.points" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.points }"
              placeholder="请输入积分价格"
              min="0"
            />
            <div v-if="validationErrors.points" class="error-message">{{ validationErrors.points }}</div>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">商品图片</label>
          <div class="image-upload">
            <div v-if="product.image" class="image-preview">
              <img :src="product.image" alt="商品图片预览" />
              <button class="remove-image" @click="removeImage">
                删除
              </button>
            </div>
            <div v-else class="upload-placeholder" @click="triggerFileUpload">
              <span>点击上传商品图片</span>
              <input 
                type="file" 
                ref="fileInput" 
                style="display: none" 
                accept="image/*" 
                @change="handleFileUpload" 
              />
            </div>
          </div>
        </div>

        <div class="form-group">
          <label for="product-description" class="form-label">商品描述</label>
          <textarea 
            id="product-description" 
            v-model="product.description" 
            class="admin-form-input description-editor" 
            placeholder="请输入商品描述"
            rows="5"
          ></textarea>
        </div>

        <div class="form-row">
          <div class="form-group half">
            <label for="product-stock" class="form-label">库存数量 <span class="required">*</span></label>
            <div class="stock-input-group">
              <input 
                type="number" 
                id="product-stock" 
                v-model.number="product.stock" 
                class="admin-form-input" 
                :class="{ 'input-error': validationErrors.stock }"
                placeholder="请输入库存数量"
                min="-1"
                :disabled="isUnlimitedStock"
              />
              <div class="stock-checkbox">
                <input type="checkbox" id="unlimited-stock" v-model="isUnlimitedStock">
                <label for="unlimited-stock">无限库存</label>
              </div>
            </div>
            <div v-if="validationErrors.stock" class="error-message">{{ validationErrors.stock }}</div>
          </div>
          
          <div class="form-group half">
            <label for="product-status" class="form-label">状态 <span class="required">*</span></label>
            <select 
              id="product-status" 
              v-model="product.status" 
              class="admin-form-input" 
              :class="{ 'input-error': validationErrors.status }"
            >
              <option value="active">上架中</option>
              <option value="inactive">下架</option>
            </select>
            <div v-if="validationErrors.status" class="error-message">{{ validationErrors.status }}</div>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <button class="admin-btn" @click="cancelEdit">取消</button>
        <button class="admin-btn admin-btn-primary" @click="saveProduct">保存</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PointEdit',
  data() {
    return {
      isEditMode: false,
      productId: null,
      loading: false,
      error: null,
      product: {
        name: '',
        category: '',
        points: 0,
        description: '',
        image: null,
        stock: 0,
        status: 'inactive'
      },
      isUnlimitedStock: false,
      validationErrors: {}
    }
  },
  watch: {
    isUnlimitedStock(newValue) {
      if (newValue) {
        this.product.stock = -1;
      } else if (this.product.stock === -1) {
        this.product.stock = 0;
      }
    }
  },
  created() {
    // 检查是否是编辑模式
    this.productId = this.$route.params.id;
    this.isEditMode = !!this.productId;
    
    if (this.isEditMode) {
      this.fetchProductData();
    }
  },
  methods: {
    fetchProductData() {
      this.loading = true;
      this.error = null;
      
      // 模拟API请求延迟
      setTimeout(() => {
        // 这里应该是实际的API调用
        // 现在使用模拟数据
        const sampleProduct = this.getSampleProductById(this.productId);
        
        if (sampleProduct) {
          this.product = { ...sampleProduct };
          // 如果库存为-1，设置为无限库存
          this.isUnlimitedStock = this.product.stock === -1;
        } else {
          this.error = '找不到该商品或已被删除';
        }
        
        this.loading = false;
      }, 500);
    },
    getSampleProductById(id) {
      const products = [
        {
          id: '1',
          name: '环保竹吸管套装',
          category: 'physical',
          points: 500,
          description: '可重复使用的环保竹吸管，替代一次性塑料吸管，包含5根竹吸管和1个清洁刷',
          image: 'https://via.placeholder.com/300x300',
          stock: 100,
          status: 'active'
        },
        {
          id: '2',
          name: '10元咖啡店优惠券',
          category: 'voucher',
          points: 200,
          description: '可在全国连锁咖啡店使用的10元代金券，有效期3个月',
          image: 'https://via.placeholder.com/300x300',
          stock: 500,
          status: 'active'
        }
      ];
      
      return products.find(p => p.id === id);
    },
    triggerFileUpload() {
      this.$refs.fileInput.click();
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      // 检查文件类型
      if (!file.type.match('image.*')) {
        alert('请上传图片文件');
        return;
      }
      
      // 模拟上传
      const reader = new FileReader();
      reader.onload = (e) => {
        this.product.image = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    removeImage() {
      this.product.image = null;
      // 清除文件输入值
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    },
    validateForm() {
      let isValid = true;
      this.validationErrors = {};
      
      if (!this.product.name.trim()) {
        this.validationErrors.name = '请输入商品名称';
        isValid = false;
      }
      
      if (!this.product.category) {
        this.validationErrors.category = '请选择商品分类';
        isValid = false;
      }
      
      if (!this.product.points || this.product.points <= 0) {
        this.validationErrors.points = '请输入有效的积分价格';
        isValid = false;
      }
      
      if (this.product.stock === undefined || (this.product.stock < -1) || (this.product.stock === 0 && this.product.status === 'active')) {
        this.validationErrors.stock = '请输入有效的库存数量';
        isValid = false;
      }
      
      if (!this.product.status) {
        this.validationErrors.status = '请选择商品状态';
        isValid = false;
      }
      
      return isValid;
    },
    saveProduct() {
      if (!this.validateForm()) {
        return;
      }
      
      // 这里应该调用API保存商品
      console.log('保存商品:', this.product);
      
      // 模拟保存成功
      alert(this.isEditMode ? '商品更新成功！' : '商品添加成功！');
      this.$router.push('/admin/points');
    },
    cancelEdit() {
      if (this.isEditMode) {
        const confirmed = confirm('确定要放弃编辑吗？未保存的内容将会丢失。');
        if (confirmed) {
          this.$router.push('/admin/points');
        }
      } else {
        this.$router.push('/admin/points');
      }
    },
    retryLoading() {
      if (this.isEditMode) {
        this.fetchProductData();
      } else {
        this.error = null;
      }
    }
  }
}
</script>

<style scoped>
.point-edit {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
}

.loading-spinner {
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top: 4px solid #1890ff;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 16px;
}

.point-form {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.form-section {
  padding: 24px;
}

.form-group {
  margin-bottom: 24px;
}

.form-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.form-group.half {
  flex: 1;
  margin-bottom: 0;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

.input-error {
  border-color: #ff4d4f;
}

.error-message {
  font-size: 14px;
  color: #ff4d4f;
  margin-top: 4px;
}

.image-upload {
  margin-top: 8px;
}

.upload-placeholder {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 32px;
  text-align: center;
  color: #999;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-placeholder:hover {
  border-color: #40a9ff;
  color: #40a9ff;
}

.image-preview {
  position: relative;
  width: 100%;
  max-width: 300px;
  border-radius: 4px;
  overflow: hidden;
}

.image-preview img {
  width: 100%;
  display: block;
}

.remove-image {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.remove-image:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.description-editor {
  resize: vertical;
}

.stock-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stock-checkbox {
  display: flex;
  align-items: center;
  gap: 4px;
}

.form-actions {
  padding: 16px 24px;
  background-color: #f5f5f5;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 